<?php
namespace app\common\service;

use app\admin\model\Cate;
use app\admin\traits\Result;
use think\Db;
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/7/13
 * Time: 17:29
 */
class WxpayService
{
	
	
	//公众号支付
    public static function wechatpay($order_id,$type=1,$user_id,$source){
        if (!$order_id) {
			return ['code'=>'0','msg'=>'确少订单id']; 
        }
        try{
			/*if($type == 1){
				$order_info = Db::name('course_order')->where('id',$order_id)->find();
				$title = '购买课程';
			}elseif($type == 2){
				$order_info = Db::name('course_order')->where('id',$order_id)->find();
				$title = '购买服务';
			}else{
				return ['code'=>'0','msg'=>'订单类型错误']; 
			}*/
			$order_info = Db::name('course_order')->where('id',$order_id)->find();
			$type = $order_info['type'];
			if($type == 1){
				$title = '购买课程';
			}elseif($type == 2){
				$title = '购买服务';
			}else{
				return ['code'=>'0','msg'=>'订单类型错误']; 
			}
			
			require_once ROOT_PATH.'extend/WeiXinpay/wxpay.php';
			
			if(empty($order_info)){
				$arr = array('code' => 0, 'msg' => '订单不存在');
				return $arr;
				exit();
			}
			if($order_info['status'] != 1){
				$arr = array('code' => 0, 'msg' => '订单不是待支付状态');
				return $arr;
				exit();
			}
			if ($order_info['user_id'] != $user_id) {
				$arr = array('code' => 0, 'msg' => '不能支付其他人的订单');
				return $arr;
				exit();
			}
			if($order_info['is_pay'] == 1){
				$arr = array('code' => 0, 'msg' => '已经支付过了');
				return $arr;
				exit();
			}
			
            $openId = Db::name('member')->where('id',$user_id)->value('openid');
            if (!$openId) {
				return ['code'=>'0','msg'=>'用户状态异常,请重新进入']; 
            }

			$price = $order_info['order_money'];
            $input = new \WxPayUnifiedOrder();
            $input->SetBody($title);
            $input->SetOut_trade_no($order_info['order_sn']);
            $input->SetTotal_fee(floatval($price)*100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 3600));
            $input->SetGoods_tag($title.trim($order_info['order_sn']));
            $input->SetAttach($type);
            //$domain = Request::domain();
            $domain = config('app_host');
			$input->SetNotify_url($domain.'/api/login/wxnotify');
			
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);
            $order = \WxPayApi::unifiedOrder($input);
            //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
			
            if($order['return_code'] == 'FAIL' || $order['result_code'] == 'FAIL'){
				return ['code'=>'0','msg'=>$order['err_code_des']??$order['return_msg']]; 
            }
			//dump($order);die;
            $arr = array();
            $arr['appId'] = $order['appid'];
            $arr['nonceStr'] = $order['nonce_str'];
            $arr['package'] = "prepay_id=".$order['prepay_id'];
            //$arr['mch_id'] = $order['mch_id'];
            //$arr['prepayid'] = $order['prepay_id'];
            $arr['signType'] = "MD5";
            $arr['timeStamp'] = (string)time();
            $str = self::ToUrlParams($arr);
            $jmstr = $str."&key=".\WxPayConfig::KEY;
            $arr['paySign'] = strtoupper(MD5($jmstr));
			return ['code'=>'1','msg'=>'success','data'=>$arr]; 
        }catch(\Exception $e){
			return ['code'=>'0','msg'=>$e->getMessage()];

        }
    }
   
	
	//构建字符串
	private function ToUrlParams($urlObj)
	{
		$buff = "";
		foreach ($urlObj as $k => $v)
		{
			if($k != "sign"){
				$buff .= $k . "=" . $v . "&";
			}
		}
		
		$buff = trim($buff, "&");
		return $buff;
	}

}